package com.netkiller.mailmonitor.workflow.impl.task;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.netkiller.mailmonitor.entity.AppUser;
import com.netkiller.mailmonitor.entity.BlobHistory;
import com.netkiller.mailmonitor.entity.LogMessage;
import com.netkiller.mailmonitor.service.AppFileService;
import com.netkiller.mailmonitor.service.AppUserService;
import com.netkiller.mailmonitor.service.BlobHistoryService;
import com.netkiller.mailmonitor.service.ContextIOService;
import com.netkiller.mailmonitor.service.LogMessageService;
import com.netkiller.mailmonitor.util.UserUtil;
import com.netkiller.mailmonitor.vo.AppProperties;
import com.netkiller.mailmonitor.workflow.AbstractWorkflowTask;
import com.netkiller.mailmonitor.workflow.WorkflowContext;
import com.netkiller.mailmonitor.workflow.WorkflowExecutionException;
import com.netkiller.mailmonitor.workflow.impl.context.AuthorizeContextIOForAllDomainUsersContext;

public class UserListTask extends AbstractWorkflowTask {
	
	@Autowired
	AppProperties appProperties;

	@Autowired private LogMessageService logMessageService;
	
	@Autowired
	AppUserService appUserService;

	@Autowired
	AppFileService appFileService;
	

	@Autowired
	private ContextIOService contextIOService;
	

	@Autowired
	BlobHistoryService blobHistoryService;

	@Override
	public WorkflowContext execute(WorkflowContext context)
			throws WorkflowExecutionException {
		// TODO Auto-generated method stub
		AuthorizeContextIOForAllDomainUsersContext thisContext = (AuthorizeContextIOForAllDomainUsersContext) context;
		String email = thisContext.getAdminEmail();
		LogMessage logMessage = new LogMessage();
		logMessage.setMessage("Started User List Generation");
		logMessageService.save(logMessage);
		
		try {
			generateCSVOfUsers(email);
			LogMessage logMessage1 = new LogMessage();
			logMessage1.setMessage("User List Generated and is available for download");
			logMessageService.save(logMessage1);
		} catch (Exception e) {
			LogMessage logMessage1 = new LogMessage();
			logMessage1.setMessage("User List Generation failed");
			logMessageService.save(logMessage1);
		}
		
		
		return context;
	}

	private void generateCSVOfUsers(String adminEmail) throws IOException {
		List<AppUser> existingUsers = appUserService.getAllUsers();
		StringBuilder sb = new StringBuilder("Sr.No.,Email,Status\n");
		Collections.sort(existingUsers, new Comparator<AppUser>() {
			@Override
			public int compare(AppUser o1, AppUser o2) {
				return o1.getEmail().compareTo(o2.getEmail());
			}
		});
		
		int index = 0;
		Date toDate = new Date();
		Date  fromDate = UserUtil.setDateRange(toDate, false);
		for(AppUser appUser: existingUsers){
			String status = "";
			if(StringUtils.isBlank(appUser.getContextioId())){
				status = "Not Authorized";
			}else{
				String response = contextIOService.fetchMailsByUser(appUser, fromDate,
						toDate);
					if (response.equalsIgnoreCase("[error]")){
						status = "Access Revoked";
					} else {
						status = "Active";
					}
			}
			
			sb.append(++index + "," + appUser.getEmail() +"," + status +"\n");
			
		}
		
	//	System.out.println(sb);
		String fileName = "User List" + "_" + new Date() + ".csv";
		String blobKeyStr = appFileService.saveFileToBlobStore(sb.toString(),
				fileName);
		
		BlobHistory blobHistory = new BlobHistory();
		blobHistory.setBlobKeyStr(blobKeyStr);
		blobHistory.setCreatedBy(adminEmail);
		blobHistory.setDomainName(UserUtil.getDomain(adminEmail));
		blobHistory.setFileName(fileName);
		SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
		String month_name = month_date.format(toDate);
		blobHistory.setMonth(month_name);
		blobHistoryService.save(blobHistory);
	}

}
